package com.wy.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.github.pagehelper.PageInfo;
import com.wy.common.Result;
import com.wy.dto.GoodsInfoDto;
import com.wy.entity.GoodsImage;
import com.wy.entity.GoodsInfo;
import com.wy.entity.UserInfo;
import com.wy.service.GoodsImageService;
import com.wy.service.GoodsInfoService;
import com.wy.service.UserInfoService;
import com.wy.util.EmailSender;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Author:王渝
 * @Date: 2022/12/1  15:23
 * @Version 1.0
 */
@RestController
@Slf4j
@RequestMapping("/goodsInfo")
public class GoodsInfoController {

    @Autowired
    private GoodsInfoService goodsInfoService;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private EmailSender emailSender;

    @Autowired
    private GoodsImageService goodsImageService;


    @Value("${file.url}")
    private String url;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 根据状态分页查询
     * @param currentPage 当前页
     * @param pageSize 一页的数量
     * @param status 状态状态（1未审核 2审核通过 3审核未通过 4已完成交易 5流拍）
     * @return
     */
    //@Cacheable(value = "goodsInfoCache",key = "#currentPage + '_'+ #pageSize + '_' + #status")
    @RequestMapping("/getAll/{currentPage}/{pageSize}/{status}")
    public Result<PageInfo<GoodsInfo>> queryAllInfoByStatus(@PathVariable int currentPage,@PathVariable int pageSize,@PathVariable String status){
        PageInfo<GoodsInfo> pageInfo = goodsInfoService.queryPage(currentPage, pageSize, status);
        return Result.success(pageInfo);
    }

    //@Cacheable(value = "goodsInfoCache",key = "#userId +'_' + #currentPage + '_'+ #pageSize + '_' + #status")
    @RequestMapping("/getAll/{currentPage}/{pageSize}/{status}/{userId}")
    public Result<PageInfo<GoodsInfo>> queryAllInfoByStatusAndUserId(@PathVariable int currentPage,@PathVariable int pageSize,@PathVariable String status,@PathVariable Long userId){
        PageInfo<GoodsInfo> pageInfo = goodsInfoService.queryPageByUserId(currentPage, pageSize, status,userId);
        return Result.success(pageInfo);
    }
    /**
     * 根据商品id查询详细信息
     * @param goodsId 商品id
     * @return
     */
    @RequestMapping("/detail/{goodsId}")
    public Result<GoodsInfoDto> queryDetailById(@PathVariable Long goodsId){
        GoodsInfoDto goodsInfoDto = goodsInfoService.queryDetailById(goodsId);
        return Result.success(goodsInfoDto);
    }

    /**
     * 根据商品id查询详细信息
     * @param goodsId 商品id
     * @return
     */
    @RequestMapping("/sellDetail/{goodsId}")
    public Result<GoodsInfoDto> queryDetailById2(@PathVariable Long goodsId){
        GoodsInfoDto goodsInfoDto = goodsInfoService.queryDetailById2(goodsId);
        return Result.success(goodsInfoDto);
    }
    /**
     * 根据类型分页查询
     * @param currentPage 当前页
     * @param pageSize 一页的数量
     * @param type 类型
     * @return
     */
    //@Cacheable(value = "goodsInfoCache",key =  "'type' + '_' + #currentPage + '_' +#pageSize +'_' + #type")
    @RequestMapping("/getAll/{currentPage}/{pageSize}")
    public Result<PageInfo<GoodsInfo>> queryAllInfoByType(@PathVariable int currentPage,
                                                          @PathVariable int pageSize,String type){
        PageInfo<GoodsInfo> pageInfo = goodsInfoService.queryPageByType(currentPage, pageSize, type);
        return Result.success(pageInfo);
    }

    /**
     * 添加商品
     * @param goodsInfo
     * @return
     */
    //@CacheEvict(value = "goodsInfoCache",allEntries = true)
    @RequestMapping("/addGoods")
    public Result<String> addGoods(@RequestBody GoodsInfo goodsInfo){

        boolean save = goodsInfoService.addGoods(goodsInfo);
        if(save){
            return Result.success("发布成功");
        }else {
            return Result.error("发布失败");
        }

    }

    /**
     * 通过商品id移除商品
     * @param goodsId
     * @return
     */
    //@CacheEvict(value = "goodsInfoCache",allEntries = true)
    @RequestMapping("/removeGoods/{goodsId}")
    public Result<String> removeGoods(@PathVariable Long goodsId){
        boolean b = goodsInfoService.removeById(goodsId);
        if(b){
            return Result.success("删除成功");
        }
        return Result.error("删除失败");
    }

    /**
     * 审核商品
     * @param goodsId
     * @return
     */
    //@CacheEvict(value = "goodsInfoCache",allEntries = true)
    @RequestMapping("/passGoods/{goodsId}")
    public Result<String> passGoods(@PathVariable Long goodsId){
        redisTemplate.delete("goodsInfo");
        LambdaUpdateWrapper<GoodsInfo> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.set(GoodsInfo::getStatus,2);
        lambdaUpdateWrapper.eq(GoodsInfo::getGoodsId,goodsId);
        //更新商品状态为审核通过
        boolean update = goodsInfoService.update(lambdaUpdateWrapper);

        if(update){
            //查询用户邮箱
            String email = goodsInfoService.queryEmailByGoodsId(goodsId);
            if(email != null && !"".equals(email)){
                //发送邮箱
                emailSender.send(email,"您好!<br/>您在MyShop发布的商品审核通过。");
                return Result.success("更新成功");
            }
            return Result.error("邮箱发送失败");
        }

        return Result.error("更新失败");
    }

    //@CacheEvict(value = "goodsInfoCache",allEntries = true)
    @RequestMapping("/unPassGoods")
    public Result<String> unPassGoods(@RequestBody GoodsInfo goodsInfo){
        LambdaUpdateWrapper<GoodsInfo> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.set(GoodsInfo::getStatus,3);
        lambdaUpdateWrapper.eq(GoodsInfo::getGoodsId,goodsInfo.getGoodsId());
        //更新商品状态为审核通过
        boolean update = goodsInfoService.update(lambdaUpdateWrapper);

        if(update){
            //查询用户邮箱
            String email = goodsInfoService.queryEmailByGoodsId(goodsInfo.getGoodsId());
            if(email != null && !"".equals(email)){
                //发送邮箱
                emailSender.send(email,"您好!<br/>您在MyShop发布的商品审核未通过通过。<br/>原因为:" + goodsInfo.getReason());
                return Result.success("更新成功");
            }
            return Result.error("邮箱发送失败");
        }

        return Result.error("更新失败");


    }

    /**
     * 根据类型分页查询
     * @param currentPage 当前页
     * @param pageSize 一页的数量
     * @param status  1在售 2已结束
     * @return
     */
    //@Cacheable(value = "goodsInfoCache",key =  "'user' + '_' + #currentPage + '_' +#pageSize + '_' +  #status +'_'+ #userId")
    @RequestMapping("/getAllBySeller/{currentPage}/{pageSize}/{status}/{userId}")
    public Result<PageInfo<GoodsInfo>> queryAllInfoByUserId(@PathVariable int currentPage,@PathVariable int pageSize,
                                                            @PathVariable String status,@PathVariable Long  userId){
        PageInfo<GoodsInfo> pageInfo = null;
        if("1".equals(status)){
            pageInfo = goodsInfoService.queryPageByUserId(currentPage,pageSize,userId);
       }else {
            pageInfo = goodsInfoService.queryPageByUserId2(currentPage,pageSize,userId);
       }

        return Result.success(pageInfo);
    }

    /**
     * 模糊查询
     * @return
     * @param search
     */
    //@Cacheable(value = "goodsInfoCache",key =  "'search' + '_' + #search")
    @RequestMapping("/getAll/{search}")
    public Result<List<GoodsInfo>> queryAllSearch(@PathVariable String search){
        LambdaQueryWrapper<GoodsInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(GoodsInfo::getGoodsName,search);
        lambdaQueryWrapper.eq(GoodsInfo::getStatus,"2");
        List<GoodsInfo> list = goodsInfoService.list(lambdaQueryWrapper);
        for (GoodsInfo goodsInfo : list) {
            LambdaUpdateWrapper<GoodsImage> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            lambdaUpdateWrapper.eq(GoodsImage::getGoodsId,goodsInfo.getGoodsId());
            List<GoodsImage> list1 = goodsImageService.list(lambdaUpdateWrapper);
            goodsInfo.setImage(url + list1.get(0).getImage());
        }
        return Result.success(list);
    }

}
